import router from '@/router'
import axios, { AxiosError, AxiosRequestConfig, AxiosResponse } from 'axios'


const instance = axios.create({
    baseURL: (window as any).$URL,
    headers: { 'Content-type': 'application/json' }
})


instance.interceptors.request.use((config: AxiosRequestConfig): AxiosRequestConfig => {
    const token: string = localStorage.getItem('token') as string
    config.headers.Authorization = token ? token : ''
    return config
}, (err: AxiosError): Promise<AxiosError> => {
    return Promise.reject(err.request)
})


instance.interceptors.response.use((response: AxiosResponse<any>): AxiosResponse<any> => {
    return response
}, (err: AxiosError): Promise<AxiosError> => {
    if (err.response?.data.Unauthorized == 'Unauthorized' || err.response?.data.statusCode == 401) {
        localStorage.removeItem('token')
        localStorage.removeItem('userdata')
        router.push({ path: "/login" })
    }
    return Promise.reject(err.response)
})


interface PARAME { url: string, data?: {} }
export async function Get(parame: PARAME): Promise<AxiosResponse<any>> {
    const { url, data } = parame;
    try {
        return await instance.get(url, {
            params: data
        })
    } catch (error) {
        return error
    }
}


export async function Post(parame: PARAME): Promise<AxiosResponse<any>> {
    const { url, data } = parame;
    try {
        return await instance.post(url, data)
    } catch (error) {
        throw error
    }
}

